<?php

/**
 * Created by PhpStorm.
 * Common: yf
 * Date: 2018/3/3
 * Time: 下午6:21
 */
namespace App\HttpController\Api;

use App\Logic\User\UserLogic;
use App\Model\User\UserBean;
use EasySwoole\Core\Http\Message\Status;
use EasySwoole\Core\Utility\Random;
use EasySwoole\Core\Swoole\Task\TaskManager;
use App\Server\Task\RegisterTask;
use App\Utility\Validator;
use App\Msg\MsgCode;

class Common extends AbstractBase
{

    function register()
    {
        // 视图层用来验证数据
        // $phone = $this->request ()->getQueryParam ( "phone" );
        $email = $this->request()->getRequestParam("email");
        $password = $this->request()->getRequestParam("password");
        $name = $this->request()->getRequestParam("name");
        // $this->checkViewForm ( Validator::isMobile ( $phone ), MsgCode::PHONE_FORMAT_ERROR );
        $this->checkViewForm(Validator::isEmail($email), MsgCode::EMAIL_FORMAT_ERROR);
        $this->checkViewForm(Validator::length($password, 3, 6, 16), MsgCode::PASSWORD_LENGTH_ERROR);
        
        $u = new UserBean();
        $u->setUid(Random::randNumStr(3) . date("His", time()) . Random::randNumStr(2));
        // $u->setPhone ( $phone );
        $u->setEmail($email);
        $u->setName($name);
        $ip = $this->request()->getHeaders();
        $u->setIp($ip['x-real-ip'][0]);
        $u->setPassword(Md5($password));
        $u->setCreateTime(time());
        // 逻辑层控制器用来处理数据
        $ul = new UserLogic();
        $uid = $ul->register($u);
        // 投递异步任务
        TaskManager::async((new RegisterTask([
            'userinfo' => $u->toArray()
        ])));
        
        $this->jsonReturn(Status::CODE_OK, [
            'UID' => $uid
        ]);
    }

    function login()
    {
        $account = $this->request()->getRequestParam("account");
        $password = $this->request()->getRequestParam("password");
        
        $ul = new UserLogic();
        $token = $ul->Login($account, $password);
        
        $this->jsonReturn(Status::CODE_OK, [
            'token' => $token
        ]);
    }

    function checkIsLogin()
    {
        $token = $this->request()->getRequestParam("token");
        
        $this->checkViewForm(Validator::isEmpty($token), MsgCode::TOKEN_IS_NULL);
        
        if ((new UserLogic())->checkIsLogin($token)) {
            $this->jsonReturn(MsgCode::USER_IS_LOGIN, []);
        } else {
            $this->jsonReturn(MsgCode::USER_NOT_LOGIN, []);
        }
    }
  
}